//
//  Dictionary+YDDataModel.swift
//  YD_DataModel
//
//  Created by 钟志远 on 2020/4/1.
//  Copyright © 2020 alyadan. All rights reserved.
//

import Foundation

public extension Dictionary where Key == String, Value == Any {
    func getValue(keyPath: String) -> [String: Any]? {
        
        var tmp: [String: Any]?
        tmp = self
        
        let keys = keyPath.components(separatedBy: ".")
        for key in keys {
            if key == "" {
                continue
            }
            tmp = tmp?[key] as? [String: Any]
        }
        
        return tmp
    }
    
    func getArrayValue(keyPath: String) -> [Any]? {
        
        var tmp: [String: Any]?
        tmp = self
        
        let keys = keyPath.components(separatedBy: ".")
        for (index, key) in keys.enumerated() {
            let tmp_1 = tmp?[key] as? [String: Any]
            if tmp_1 == nil {
                if index != keys.count - 1 {
                    print("keyPath is invalid")
                    return nil
                }
                
                if let data = tmp?[key] as? [Any] {
                    return data
                }
            }
            
            tmp = tmp_1
        }
        
        return nil
    }
}
